#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>

// 172.29.140.142 这是wsl的内网地址
using websocketsvr = websocketpp::server<websocketpp::config::asio>;
using message_ptr = websocketsvr::message_ptr;

using std::cout;
using std::endl;
using websocketpp::lib::bind;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
// websocket连接成功的回调函数

void OnOpen(websocketsvr *server, websocketpp::connection_hdl hdl)
{
    cout << "连接成功" << endl;
}
// websocket连接成功的回调函数

void OnClose(websocketsvr *server, websocketpp::connection_hdl hdl)
{
    cout << "连接关闭" << endl;
}
// websocket连接收到消息的回调函数

void OnMessage(websocketsvr *server, websocketpp::connection_hdl hdl, message_ptr msg)
{
    cout << "收到消息" << msg->get_payload() << endl;
    // 收到消息将相同的消息发回给websocket客⼾端

    server->send(hdl, msg->get_payload(), websocketpp::frame::opcode::text);
}
// websocket连接异常的回调函数

void OnFail(websocketsvr *server, websocketpp::connection_hdl hdl)
{
    cout << "连接异常" << endl;
}
void OnHttp(websocketsvr *server, websocketpp::connection_hdl hdl)
{
    std::cout << "handle http request\n";
    websocketsvr::connection_ptr con = server->get_con_from_hdl(hdl);
    std::stringstream ss;
    ss << "<!doctype html><html><head>"
       << "<title>hello websocket</title><body>"
       << "<h1>hello websocketpp</h1>"
       << "</body></head></html>";
    con->set_body(ss.str());
    con->set_status(websocketpp::http::status_code::ok);
}
int main()
{
    websocketsvr server;
    // 什么日志也不打印
    server.set_access_channels(websocketpp::log::alevel::none);
    server.init_asio();
    server.set_http_handler(std::bind(&OnHttp, &server, ::_1));
    server.set_open_handler(bind(&OnOpen, &server, ::_1));
    server.set_close_handler(bind(&OnClose, &server, _1));
    server.set_message_handler(bind(&OnMessage, &server, _1, _2));
    // 监听8888 端⼝

    server.listen(8888);
    // 开始接收tcp连接

    server.start_accept();
    // 开始运⾏服务器

    server.run();
    return 0;
}
